#include "dbhelper.h"


DbHelper::DbHelper()
{
    db = QSqlDatabase::addDatabase("QODBC");
    db.setHostName("127.0.0.1");
    db.setPort(3306);
    db.setUserName("root");
    db.setPassword("wb412412");
    db.setDatabaseName("MySQL57");
    bool res = db.open();

    if(res == true){
        qDebug() << "MySql open success" << endl;
        query = new QSqlQuery;
    }else{
        qDebug() << "MySql open fail, error info: " << db.lastError();
    }
}

DbHelper *DbHelper::getInstance()
{
    if(instance == NULL){
        instance = new DbHelper();
    }

    return instance;
}

bool DbHelper::regist(const QString &name, const QString &pswd)
{

    qDebug() << "regist name: " << name;
    qDebug() << "regist pswd " << pswd;

    QString strsql = QString("insert into user(name, pwd) values('%1', '%2');").arg(name).arg(pswd);

    bool res = query->exec(strsql);
    if(false == res){
        qDebug() << "exec error,error info" << query->lastError();
    }

    return res;
}

bool DbHelper::login(const QString &name, const QString &pswd)
{
    qDebug() << "login name: " << name;
    qDebug() << "login pswd " << pswd;

    QString strsql =QString("select * from user where name='%1';").arg(name);

    bool res = query->exec(strsql);
    if(false == res){
        qDebug() << "exec error,error info" << query->lastError();
    }

    if(query->next() == false){
        // 没找到账号，登录失败
        return false;
    }

    if(query->value("pwd") != pswd){
        // 没找到密码，登录失败
        return false;
    }

    return true;
}
